<?php

declare(strict_types=1);

namespace Dreamcat\ApiDocTest\Utils;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use JsonSchema\Uri\Retrievers\UriRetrieverInterface;

/**
 * guzzle的url获取器
 * @author vijay
 */
class GuzzleUriRetriever implements UriRetrieverInterface
{
    private Client $client;
    private string $lastType = "";

    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * @inheritDoc
     * @throws GuzzleException
     */
    public function retrieve($uri)
    {
        if (str_starts_with($uri, "file://")) {
            $content = file_get_contents($uri);
            $this->lastType = "application/json";
            return $content;
        } else {
            $response = $this->client->get($uri);
            $this->lastType = $response->getHeader("Content-Type")[0];
            return strval($response->getBody());
        }
    }

    /**
     * @inheritDoc
     */
    public function getContentType(): string
    {
        return $this->lastType;
    }
}

# end of file
